<template>
    <div class="content">
        <el-row :gutter="10">
            <el-col :md="6" class="deptContent">
                <div class="query">
                    <el-form :inline="true" :model="deptForm" label-width="auto">
                        <el-form-item label="部门名称：">
                            <el-input clearable v-model="deptForm.deptName" style="width: 200px" placeholder="请输入部门名称查询"
                                @blur="getDeptTreeData" />
                        </el-form-item>
                    </el-form>
                </div>
                <div class="tree">
                    <el-tree :data="deptTreeData" :expand-on-click-node="false" default-expand-all :props="{
                        children: 'children',
                        label: 'deptName',
                        value: 'deptId'
                    }" @node-click="selectDept" v-loading="deptLoading" element-loading-text="数据加载中..." />
                </div>
            </el-col>
            <el-col :md="18">
                <div class="query" v-if="showQuery">
                    <el-form :inline="true" :model="form" label-width="auto">
                        <el-form-item label="用户名称：">
                            <el-input clearable v-model="form.username" style="width: 200px" placeholder="请输入用户名查询" />
                        </el-form-item>
                        <el-form-item label="手机号码：">
                            <el-input clearable v-model="form.phone" style="width: 200px" placeholder="请输入手机号查询" />
                        </el-form-item>
                        <el-form-item label="用户状态：">
                            <el-select clearable v-model="form.status" placeholder="请选择状态查询" style="width: 200px">
                                <el-option label="正常" value="0" />
                                <el-option label="禁用" value="1" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label-width="200">
                            <el-button type="primary" @click="getData" :icon="Search">查询</el-button>
                            <el-button @click="reset" :icon="Refresh">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="fun">
                    <div class="left">
                        <el-button type="primary" @click="userAddOrEdit('')" plain :icon="Plus">新增</el-button>
                        <el-popconfirm title="请确认执行批量删除操作?" confirm-button-text="确认" cancel-button-text="取消"
                            @confirm="deleteUser('batch')">
                            <template #reference>
                                <el-button type="danger" :disabled="ids.length == 0" plain
                                    :icon="Delete">批量删除</el-button>
                            </template>
                        </el-popconfirm>
                    </div>
                    <div class="right">
                        <el-tooltip :content="showQuery ? '隐藏搜索栏' : '展示搜索栏'" placement="top">
                            <el-button :icon="TurnOff" circle @click="showQuery = false" v-if="showQuery" />
                            <el-button :icon="Open" circle @click="showQuery = true" v-else />
                        </el-tooltip>
                        <el-tooltip content="刷新" placement="top">
                            <el-button :icon="Refresh" circle @click="getData()" />
                        </el-tooltip>
                    </div>
                </div>
                <div class="table">
                    <el-table empty-text="暂无数据" :show-overflow-tooltip="true" :data="tableData" v-loading="loading"
                        element-loading-text="数据加载中..."
                        :header-cell-style="{ background: 'var(--table-title-color)', color: 'var(--table-title-font-color)' }"
                        @selection-change="handleSelectionChange" border>
                        <el-table-column type="selection" width="55" />
                        <el-table-column prop="userNo" label="用户账号" />
                        <el-table-column prop="username" label="用户名称" />
                        <el-table-column prop="phone" label="手机号码" />
                        <el-table-column prop="pic" label="头像">
                            <template #default="scope">
                                <el-avatar :size="40" :src="url + scope.row.headPic" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="用户状态">
                            <template #default="scope">
                                <el-switch v-model="scope.row.status" :active-value="'0'" :inactive-value="'1'"
                                    inline-prompt active-text="正常" inactive-text="禁用"
                                    @change="changeStatus(scope.row.status, scope.row.userId)" />
                            </template>
                        </el-table-column>
                        <el-table-column :fixed="$isMobile() ? false : 'right'" label="操作" width="250">
                            <template #default="scope">
                                <el-button text type="primary" size="small" :icon="Edit"
                                    @click="userAddOrEdit(scope.row.userId)">修改</el-button>
                                <el-popconfirm title="请确认执行删除操作?" @confirm="deleteUser(scope.row.userId)">
                                    <template #reference>
                                        <el-button text type="primary" size="small" :icon="Delete">删除</el-button>
                                    </template>
                                </el-popconfirm>
                                <el-popconfirm title="请确认执行下线操作?" @confirm="offline(scope.row.userId)">
                                    <template #reference>
                                        <el-button text type="primary" size="small" :icon="Bottom">下线</el-button>
                                    </template>
                                </el-popconfirm>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <el-config-provider>
                    <el-pagination v-model:current-page="page.currentPage" v-model:page-size="page.pageSize"
                        :page-sizes="[10, 20, 30, 40]" :pager-count="$isMobile() ? 5 : 7"
                        :layout="$isMobile() ? 'prev,pager,next' : 'total, sizes, prev, pager, next, jumper'"
                        :background="!$isMobile()" :total="page.total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </el-config-provider>
            </el-col>
        </el-row>
        <addOrEdit ref="addEdit" @serversUpdated="getData"></addOrEdit>
    </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import api from '@/api';
import { Delete, Edit, Bottom, Search, Plus, TurnOff, Open, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import addOrEdit from './addOrEdit.vue';

const loading = ref(false)
const deptLoading = ref(false)
const form = ref({})
const page = ref({ pageSize: 10, pageNum: 1, currentPage: 0, total: 0 })
const tableData = ref([])
const url = ref(import.meta.env.VITE_BASE_URL + '/system/file/download/')
const ids = ref([])
const addEdit = ref()
const deptForm = ref({})
const deptTreeData = ref([])
const showQuery = ref(true)

//获取数据
const getData = async () => {
    loading.value = true
    let params = { pageNum: page.value.pageNum, pageSize: page.value.pageSize, ...form.value }
    const res = await api.get('/author/user/pageList', params)
    if (res.data.code === 200) {
        tableData.value = res.data.data.records
        page.value.currentPage = res.data.data.current
        page.value.total = res.data.data.total
        loading.value = false
    } else {
        ElMessage.error(res.data.msg)
    }
}
//切换页
const handleSizeChange = (val) => {
    page.value.pageSize = val
    getData()
}
const handleCurrentChange = (val) => {
    page.value.pageNum = val
    getData()
}
//重置查询条件
const reset = () => {
    form.value = {}
    getData()
}
const handleSelectionChange = (val) => {
    let userIds = val.map(item => item.userId)
    ids.value = userIds
}
//新增或修改
const userAddOrEdit = (userId) => {
    addEdit.value.init(userId)
}

//删除
const deleteUser = (userId) => {
    let params
    if (userId !== 'batch') {
        params = [userId]
    } else {
        if (ids.value.length === 0) {
            ElMessage.warning('请先选择需要删除的行，再做操作!')
            return
        }
        params = ids.value
    }
    api.post('/author/user/delete', params).then(res => {
        if (res.data.code === 200) {
            ElMessage.success(res.data.msg)
            getData()
        } else {
            ElMessage.error(res.data.msg)
        }
    })
}
//修改状态
const changeStatus = (val, userId) => {
    const params = { 'userId': userId, 'status': val }
    api.post('/author/user/edit', params).then(res => {
        if (res.data.code === 200) {
            ElMessage.success(res.data.msg)
        } else {
            ElMessage.error(res.data.msg)
        }
    })
}
//用户离线
const offline = (userId) => {
    api.post('/author/user/offline', { userId }).then(res => {
        if (res.data.code === 200) {
            ElMessage.success(res.data.msg)
        } else {
            ElMessage.error(res.data.msg)
        }
    })
}
//获取部门树
const getDeptTreeData = async () => {
    deptLoading.value = true
    const res = await api.get('/author/dept/treeData', deptForm.value)
    if (res.data.code === 200) {
        deptTreeData.value = res.data.data
    } else {
        ElMessage.error(res.data.msg)
    }
    deptLoading.value = false
}
//选择部门
const selectDept = (data) => {
    form.value.deptId = data.deptId
    getData()
}

onMounted(() => {
    getDeptTreeData()
    getData()
})

</script>
<style lang="less" scoped>
.deptContent {
    border-right: 0.5px solid var(--boder-color);
}

.tree {
    padding: 10px;
}
</style>